from tkinter import *
from random import randint
import time 


class MyBall:
    width = 800
    height = 600
    vx = 2
    vy = 2
    D = 20
    DURATION = 0.001   # sleep 时间 = 绘制的间隔
    def __init__(self,color):
        self.ball_x=randint(0,MyBall.width-MyBall.D)
        self.ball_y=randint(0,MyBall.height-MyBall.D)
        self.tk = Tk()
        self.canvas =Canvas(self.tk, width=MyBall.width, height=MyBall.height,bd=2)
        self.make_walls()
        #create a ball
        self.ball = self.canvas.create_oval(0,0,MyBall.D,MyBall.D,fill=color,outline="lightgray")
        #set ball's position
        #self.canvas.move(self.ball, self.ball_x, self.ball_y)
        self.canvas.pack()

    def make_walls(self):
        self.canvas.create_rectangle(0, 0, MyBall.width, MyBall.height, fill="white")
        
    def draw(self):
        x = 10
        y= 10 
        
        for s in range(6000):
           x = x + MyBall.vx
           y = y + MyBall.vy
           if x + MyBall.D/2 >= MyBall.width :
               MyBall.vx = -MyBall.vx
               
           if x - MyBall.D/2 <= 0 :
               print(f"x = {x} MyBall.D/2 = {MyBall.D/2}  MyBall.vx={MyBall.vx}")
               MyBall.vx = -(MyBall.vx)
               
           if y + MyBall.D/2 >= MyBall.height :
               MyBall.vy = -MyBall.vy
               
           if y - MyBall.D/2 <= 0 :
               MyBall.vy = -(MyBall.vy)
               
           self.canvas.move(self.ball, MyBall.vx, MyBall.vy)
           self.tk.update()
           time.sleep(MyBall.DURATION)
           
        self.tk.mainloop()
        
MyBall= MyBall("red")
MyBall.draw()